#include<stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include<netinet/in.h>
#include<stdlib.h>
#include <unistd.h>
#include<string.h>

#define LOG(fmt, ...) \
            printf(fmt, ##__VA_ARGS__); \
            printf("\r\n") \

#define S_IP_STR		"192.168.31.73"		/* 服务器地址 */
#define C_IP_STR		"192.168.31.73"		/* 客户端地址 */


int main()
{
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;
	/* socket */
	 int s_fd =  socket(AF_INET, SOCK_STREAM, 0);
	
	if(s_fd == -1)
	{
		perror("socket");
		exit(-1);	
	}

	/* 参数初始化 */
	memset(&s_addr,0,sizeof(struct sockaddr_in));

	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(8888);
	inet_aton(S_IP_STR, &s_addr.sin_addr);

	/* bind */
	bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));

	/* listen */
	listen(s_fd, 10);

	/* accept */
	LOG("wait connecting......");

	memset(&c_addr,0,sizeof(struct sockaddr_in));
	int clen = sizeof(struct sockaddr_in);
	int c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&clen);

	if(c_fd == -1)
	{
		perror("accept");
		exit(-1);
	}

	LOG("connect,%s\n",inet_ntoa(c_addr.sin_addr));

	/* read */
	char Readbuf[128];
       int nread = read(c_fd, Readbuf,128);
	
	if(nread == -1)
	{
		perror("read");
		exit(-1);		
	}
	else
	{
		LOG("nread:%d, context:%s\n",nread,Readbuf);
	}


	/* write */
	char *Writebuf = "liuxinishandsome";
	int nwrite = write(c_fd, Writebuf,strlen(Writebuf));
	
	return 0;
}
